package com.kalaqia.wechat.auth.di;

import android.content.Context;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;


/**
 * function:
 * project:WeChatModule
 * describe:
 * created owner:kalaqia 421407393@qq.com
 * created date:2017/9/1 14:53
 */
//<editor-fold desc="version update log">
// updare owner:kalaqia  421407393@qq.com
// update datetime:2017/9/1 14:53 
// update remark:
//</editor-fold>
public class WeChatAuthPresenter {

    private Context context;
    private final String APP_KEY = "wx8e92d3a32c0808f1";

    public WeChatAuthPresenter(Context context) {
        this.context = context;
    }

    public void login() {
        IWXAPI mApi = WXAPIFactory.createWXAPI(context.getApplicationContext(), APP_KEY);
        // 将app注册到微信
        mApi.registerApp(APP_KEY);
        Observable.just(mApi)
                // filter WeChat is installed
                .filter(new Predicate<IWXAPI>() {
                    @Override
                    public boolean test(@NonNull IWXAPI mApi) throws Exception {
                        return mApi.isWXAppInstalled();
                    }
                })
                //request auth
                .map(new Function<IWXAPI, Boolean>() {
                    @Override
                    public Boolean apply(@NonNull IWXAPI mApi) throws Exception {
                        SendAuth.Req req = new SendAuth.Req();
                        req.scope = "snsapi_userinfo";
                        req.state = "wechat_sdk_demo_test";
                        return mApi.sendReq(req);
                    }
                }).observeOn(Schedulers.io())
                // response auth
                .concatMap(new Function<Boolean, ObservableSource<?>>() {
                    @Override
                    public ObservableSource<?> apply(@NonNull Boolean aBoolean) throws Exception {
                        return new WeChatSendAuthRespObservable();
                    }
                })
                // post url
                .concatMap(new Function<Object, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(@NonNull Object o) throws Exception {
                        return null;
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe()
        ;

    }

}
